<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StudioService
{
    // 列表
    public static function index($data)
    {
        $auth = Auth::instance();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $studio_name= isset($data['studio_name']) ? $data['studio_name'] : '';
        if($studio_name){
            $where['studio_name'] = ['like', '%'.$studio_name.'%'];
        }else{
            $where = [];
        }


        //分页查询
        $studio = \app\admin\model\Studios::where($where)->field('*,studio_id, studio_name, country, region, contact_email')->order('id', 'desc')
            ->paginate($limit)->each(function ($item) {
                $item['country_name'] = \app\admin\model\Regions::where('region_code', $item['country'])->value('region_name');
                $item['region_name'] = \app\admin\model\Regions::where('region_code', $item['region'])->value('region_name');
            });
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }


    // 添加
    public static function add($data)
    {
        // 验证规则（可提取为静态变量或单独方法）
        static $validate;
        if (!$validate) {
            $validate = new Validate([
                'studio_id' => 'require|unique:studios,studio_id',
                'studio_name' => 'require|unique:studios,studio_name',
                'opening_date' => 'require',
                'language' => 'require',
                'status' => 'require',
                'country' => 'require',
                'region' => 'require',
                'address' => 'require',
                'location' => 'require',
                'contact_name' => 'require',
                'contact_mobile' => 'require',
                'contact_email' => 'require',
            ], [
                'studio_id.require' => 'StudioId is not empty',
                'studio_id.unique' => 'StudioId is already exists',
                'studio_name.require' => 'Studio name is not empty',
                'studio_name.unique' => 'Studio name is already exists',
                'opening_date.require' => 'Opening date is not empty',
                'language.require' => 'Language is not empty',
                'status.require' => 'Status is not empty',
                'country.require' => 'Country is not empty',
                'region.require' => 'Region is not empty',
                'address.require' => 'Address is not empty',
                'location.require' => 'Location is not empty',
                'contact_name.require' => 'Contact name is not empty',
                'contact_mobile.require' => 'Contact mobile is not empty',
                'contact_email.require' => 'Contact email is not empty',
            ]);
        }

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        Db::startTrans(); // 显式开启事务

        try {
            $result = \app\admin\model\Studios::create($data);

            if ($result) {
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Throwable $e) {
            Db::rollback();
//            $exceptionClass = get_class($e);
            return ['code' => 400, 'msg' => "System error", 'state' => 'SYSTEM_ERROR', 'data' => null];
        }
    }



    // 编辑
    public static function edit($data)
    {
        // 基本验证
        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid ID', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 移除虚拟字段
        unset($data['country_name'], $data['region_name']);

        // 验证规则（注意unique规则添加排除当前ID）
        $validate = new Validate([
            'studio_id' => 'require|unique:studios,studio_id,'.$data['id'],
            'studio_name' => 'require|unique:studios,studio_name,'.$data['id'],
            'opening_date' => 'require',
            'language' => 'require',
            'status' => 'require',
            'country' => 'require',
            'region' => 'require',
            'address' => 'require',
            'location' => 'require',
//            'longitude' => 'require',
//            'latitude' => 'require',
            'contact_name' => 'require',
            'contact_mobile' => 'require',
            'contact_email' => 'require',
        ], [
            'studio_id.require' => 'Region code is not empty',
            'studio_id.unique' => 'Region code is already exists',
            'studio_name.require' => 'Region name is not empty',
            'studio_name.unique' => 'Region name is already exists',
            'opening_date.require' => 'Opening date is not empty',
            'language.require' => 'Language is not empty',
            'status.require' => 'Status is not empty',
            'country.require' => 'Country is not empty',
            'region.require' => 'Region is not empty',
            'address.require' => 'Address is not empty',
            'location.require' => 'Location is not empty',
//            'longitude.require' => 'Longitude is not empty',
//            'latitude.require' => 'Ltitude is not empty',
            'contact_name.require' => 'Contact name is not empty',
            'contact_mobile.require' => 'Contact mobile is not empty',
            'contact_email.require' => 'Contact email is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            $result = \app\admin\model\Studios::update($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字
        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        // 查询学习馆数据
        $studio = \app\admin\model\Studios::find($data['id']);
        if (!$studio) {
            return ['code'=>400, 'msg'=>'Region does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
        }
        if ($studio->status == 'active') {
            return ['code'=>400, 'msg'=>'Region is active', 'state'=>'ACTIVE', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            $result = \app\admin\model\Studios::destroy($data['id']);

            if($result){
                // TODO删除关联数据

                // TODO转移老师、学员数据

                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    public static function select($data)
    {
//        $studio_name= isset($data['studio_name']) ? $data['studio_name'] : '';
//        if($studio_name){
//            $where['studio_name'] = ['like', '%'.$studio_name.'%'];
//        }else{
//            $where = [];
//        }

        //分页查询
        $studio = \app\admin\model\Studios::field('id,studio_id')->order('id', 'desc')->select();
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }


}
